import constants as con
from pygame.locals import *

class Scoreboard(object):
    def __init__(self,parent):
        self.selected = 1
        self.pos = (50,50)

        self.parent = parent
        self.font = parent.font

        # here's hoping we're using fixed width
        (self.width,self.height) = self.font.size('A')
        self.line_length = int( (con.window_size[0] - (self.pos[0] * 2)) / self.width)

        self.selected = 1
        self.screen = self.screen1

        self.url = 'http://xzzy.org/taxtris/query.php'
        self.task = 'Open'
        self.pos = (50,50)

        self.scores = []

    def screen1(self):
        self.fetch_url()

    def screen2(self):
        pos = self.pos
        pos = self.linedraw("%20s   %10s" % ("Username","Score"), pos)
        pos = self.linedraw("-" * 33, pos)

        for score in self.scores:
            pos = self.linedraw("%20s   %10s" % (score[0],score[1]), pos)
            if pos[1] > (con.window_size[1] - 60):
                break
        pos = (pos[0],pos[1] + 10)
        pos = self.linedraw("press enter to go back to main screen", pos)

    def screen3(self):
        self.stringdraw("this is screen 3",self.pos)
        
    def redraw(self):

        self.screen()
        
    def linedraw(self,str,pos):
        x = pos[0]
        y = pos[1]

        label = self.font.render(str, True, con.fgcolor)
        self.parent.screen.blit(label, pos)
        y += self.height

        return (x,y)

    def stringdraw(self,str,pos):

        x = pos[0]
        y = pos[1]
        
        buf = ''
        for word in str.split():
            # render if adding this word would put us over the limit
            if (len(buf) + len(word)) >= self.line_length:
                label = self.font.render(buf, True, con.fgcolor)
                self.parent.screen.blit(label, pos)
                y += self.height
                buf = word
            elif len(buf) == 0:
                buf = word
            else:
                buf = buf + ' ' + word

        if len(buf):
            label = self.font.render(buf, True, con.fgcolor)
            self.parent.screen.blit(label, (x,y))

    def inputDown(self,key):
        if key == K_RETURN:
            if self.task == 'Error':
                self.parent.state = 'Menu'
            else:
                self.next_screen()

    def next_screen(self):
        if self.selected == 1:
            print "setting to screen 2"
            self.selected += 1
            self.screen = self.screen2
        elif self.selected == 2:
            print "done, going back to menu"
            self.parent.state = 'Menu'

    def fetch_url(self):
        pos = (50,50)
        if self.task == 'Open':
            try:
                import httplib
                self.dest = httplib.HTTPConnection('xzzy.org')
                self.task = 'Submit'
            except:
                self.error = "Can't make HTTP connection."
                self.task = 'Error'

        elif self.task == 'Submit':
            try:
                self.dest.request("GET", self.url)
                self.task = 'ResponseCheck'
            except:
                self.error = "GET call failed."
                self.task = 'Error'

        elif self.task == 'ResponseCheck':

            result = self.dest.getresponse()
            self.data = result.read()
            
            if not result.reason == 'OK':
                self.error = "Failure submitting data: %s %s" % (result.status,result.reason)
                self.task = 'Error'
            else:
                self.task = 'Success'

        elif self.task == 'Error':
            str = "Error detected: %s. Press enter to continue." % (self.error)
            pos = self.stringdraw(str,pos)
        elif self.task == 'Success':
            self.selected = 2
            self.screen = self.screen2
            self.parse_data()

    def parse_data(self):
        for user in self.data.split(':'):
            chunk = user.split(',')
            if not chunk[0] == '':
                self.scores.append( chunk )
